<template>
  <component :is="currentIs"></component>
</template>

<script lang="ts">
import PageNotFound from './404.vue';
export default {
  name: 'Router.vue',
  components: {
    PageNotFound,
  },
  props: {
    router: {
      default: () => [],
    },
  },
  inject: ['history', 'publicPath'],
  data: () => {
    return {
      current: null,
    };
  },
  computed: {
    currentIs() {
      return this.current || PageNotFound;
    },
  },
  mounted() {
    this.unlisten = this.history.listen(({ location }) => {
      this.onPathChange(location);
    });
    this.onPathChange(this.history.location);
  },
  destroyed() {
    if (this.unlisten) {
      this.unlisten();
    }
  },
  methods: {
    onPathChange(location) {
      console.log(location.pathname);
      const path = location.pathname?.replace(this.publicPath, '') || '';
      console.log(this.router);
      const router = this.router.find((item) => item.path === path);
      if (router) {
        this.current = router.component;
      }
    },
  },
};
</script>

<style scoped></style>
